package com.zlm.tools.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * {@code }
 *
 * @author zlm
 * @since 2025/7/3
 */
@RestController
public class DownloadController {


    @GetMapping("/download")
    public void download(HttpServletResponse response,String filename) {
        sendFile(response,filename);
    }

    private void sendFile(HttpServletResponse response,String filename) {
        response.setHeader("Content-Disposition", "attachment;filename="+filename);
        response.setContentType("application/octet-stream");
        try(FileInputStream fis = new FileInputStream("D:\\"+filename);
            ServletOutputStream os = response.getOutputStream()
        ) {
            byte[] buffer = new byte[1024 * 10];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
                Thread.sleep(500);
                System.out.println(">>> file server send byte length: "+len);
            }
            os.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
